package 富婆梦.第一阶段.第八周Scoket.练习题;

import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @ProjectName: java-learning
 * @Package: 富婆梦.第一阶段.第八周Scoket
 * @ClassName: DailyAdviceServer
 * @Author: hemengjin
 * @Description: Scoket服务端
 * @Date:2021/9/20 9:39
 * @Version: 1.0
 */
public class DailyAdviceServer {
    String[] adviceList = {"I am A","I am B","I am C","I am D","I am E","I am F","I am G","I am H"};
    public void go(){
        try{
            ServerSocket serverSocket = new ServerSocket(8888);
            while (true){
                Socket sock = serverSocket.accept();
                System.out.println("已经有一个客户端建立连接了！");
                //使用socket连接来送出信息，送出后可以关闭
                PrintWriter writer = new PrintWriter(sock.getOutputStream());

                String advice = getAdvice();
                writer.println(advice);
                writer.close();
                System.out.println(advice);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private String getAdvice(){
        int random = (int)Math.random()*adviceList.length;
        return adviceList[random];
    }

    public static void main(String[] args) {
        DailyAdviceServer server = new DailyAdviceServer();
        server.go();
    }
}
